<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/8/7 14:34
 * Modified Time: 2019/8/7 14:34
 * Version: 2.0
 */

namespace App\Modules\Inventory\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;

class GetStoreGoodsSaleRecordCriteria extends BaseCriterias
{
    protected $store_id;

    public function __construct($store_id)
    {
        $this->store_id = $store_id;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $store_id = $this->store_id;
        $model = $model
            ->select([
                'id',
                'user_id',
                'goods_id',
                'count',
                'buying_price',
                'market_price',
                'buying_sum',
                'market_sum',
                'royalty',
                'real_price',
                'payment',
                'created_at'
            ])
            ->with(['goods' => function ($query) {
                $query
                    ->select([
                        'id',
                        'name',
                        'small_name',
                        'cat_id',
                        'image'
                    ])
                    ->with(['goodsCategory' => function ($query) {
                        $query->select(['id', 'parent_id', 'name'])
                            ->with(['parent' => function ($query) {
                                $query->select(['id', 'name']);
                            }]);
                    }])
                    ->with(['image' => function ($query) {
                        $query->select([
                            'id', 'image'
                        ]);
                    }]);
            }])
            ->with(['user' => function ($query) {
                $query->select([
                    'user.id',
                    'user.nick',
                    'picture.image as portrait'
                ])->leftJoin('picture', 'user.portrait', 'picture.id');
            }])
            ->where('store_id', $store_id)
            ->orderBy('goods_order.created_at', 'DESC');

        return $model;
    }
}